#include "SupplyBarElement.h"

SupplyBarElement::SupplyBarElement(TextureManager * textureManager, char * textureName, Vector2D position, Vector2D size, Vector2D * textureVertices, int * supplyCount)
:MenuElement(textureManager, textureName, position, size, textureVertices)
{
	this->supplyCount = supplyCount;
}
SupplyBarElement::~SupplyBarElement()
{
}
void SupplyBarElement::Draw(Vector2D parentPosition)
{
	if(label)
	{
		label->Draw(parentPosition);
	}
	if(!supplyCount || *supplyCount <= 0)
		return;
	int rowCount = 1;
	int columnCount = *supplyCount;
		
	Vector2D singleSize = size;
	singleSize.x /= *supplyCount;
	
	
	while(singleSize.x < singleSize.y)
	{
		rowCount ++;
		singleSize.y /= 2;
		singleSize.x *= 2;
		columnCount = columnCount / 2 + (columnCount%2);
	}
	
	if(singleSize.x > singleSize.y)
	{
		singleSize.x = singleSize.y;
	}
	
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrtho(0,100,100,0, -1, 1);
	
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();
	glTranslatef(0, 0, -0.5);
	
	//printf("textureIndex = %d\n", textureIndex);
	if(textureIndex >= 0)
	{
		textureManager->EnableTexture(textureIndex);
		glEnable(GL_TEXTURE_2D);
		glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
		glBlendFunc(GL_ONE, GL_ONE);
		glAlphaFunc( GL_GREATER, 0.01 );
  		glEnable( GL_ALPHA_TEST );
  		glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
		glEnable(GL_BLEND);
	}
	
	glColor4f(1,1,1,0.9);	
	int counter = 0;
	for(int y = 0; y < rowCount; y++)
	{
		for(int x = 0; x < columnCount && counter < *supplyCount; x++)
		{
			counter++;
			Vector2D vertices[4];
			vertices[0] = parentPosition + position;
			vertices[0].x += singleSize.x * x;
			vertices[0].y += singleSize.y * y;
			vertices[1] = Vector2D(vertices[0].x + singleSize.x, vertices[0].y);
			vertices[2] = Vector2D(vertices[1].x, vertices[1].y + singleSize.y);
			vertices[3] = Vector2D(vertices[0].x, vertices[2].y);
			glBegin(GL_QUADS);
			for(int i = 0; i < 4; i++)
			{
				//printf("drawing element %d at\n\t(%f, %f)\n",i, vertices[i].x, vertices[i].y);
				glTexCoord2f(textureVertices[i].x, textureVertices[i].y);
				glVertex3f(vertices[i].x, vertices[i].y, 1);
			}
			glEnd();
		}
	}
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_BLEND);
	glPopMatrix();
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_BLEND);
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
}
